<template>
  <div class="page-wrapper">
    <div class="page-header">
      <div class="search">
        <div class="search-input">
          <el-input
            class="input"
            v-model="content"
            placeholder="请输入企业名称、客户经理、产品名、或地址电话\经营范围等，多关键字用空格隔开，如“福州 代账”"
          />
        </div>
        <div class="button-group">
          <el-button class="button btn-search" type="primary" @click="list"
            >查一下</el-button
          >
          <el-button class="search-text" type="" text @click="to"
            >高级搜索</el-button
          >
          <!-- <el-button
            class='button btn-add'
            type='primary'
            plain
            @click='toOrderManagement'
            >新增订单</el-button
          > -->
        </div>
      </div>
      <div class="tools">
        <div class="count">
          检索完成 为你找到
          <span style="color: red; font-weight: 600">{{ total }}</span> 条数据
        </div>
        <div class="btn-group">
          <el-button
            size="default"
            plain
            style="margin-right: 10px"
            @click="importDialogVisible = true"
            >云财税批量导入</el-button
          >
          <el-dropdown>
            <el-button
              size="default"
              plain
              style="margin-right: 20px; width: 120px"
            >
              {{ dropdown
              }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="toSearch(null, null, '默认排序')"
                  >默认排序</el-dropdown-item
                >
                <el-dropdown-item
                  @click="toSearch('orderByTime', 'asc', '创建时间升序')"
                  >创建时间升序</el-dropdown-item
                >
                <el-dropdown-item
                  @click="toSearch('orderByTime', 'desc', '创建时间降序')"
                  >创建时间降序</el-dropdown-item
                >
                <el-dropdown-item
                  @click="toSearch('orderByXj', 'asc', '客户星级升序')"
                  >客户星级升序</el-dropdown-item
                >
                <el-dropdown-item
                  @click="toSearch('orderByXj', 'desc', '客户星级降序')"
                  >客户星级降序</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button size="default" type="primary" @click="toOrderManagement"
            >新增客户</el-button
          >
          <el-button size="default" plain @click="addDialogVisible = true"
            >批量新增</el-button
          >
          <!-- <el-button size="mini" plain disabled>批量导出</el-button> -->
        </div>
      </div>
    </div>
    <div class="content" v-loading="loading">
      <company-item
        class="company-item"
        v-for="(company, index) in companyList"
        :list="company"
        :key="'res' + index"
        @click="toCustomerDetail(company)"
      />
    </div>
    <div class="footer">
      <Pagination
        class="pagination"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="list"
      />
    </div>

    <el-dialog
      title="云财税批量导入"
      v-model="importDialogVisible"
      width="400px"
    >
      <el-upload
        ref="upload"
        v-loading="upload.isUploading"
        element-loading-text="正在上传模板 请稍候"
        :limit="1"
        action="#"
        :http-request="requestUpload"
        accept=".xlsx"
        :disabled="upload.isUploading"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip" style="color: red" name="tip">
            提示：仅允许导入“xlsx”格式文件！
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="fetchFile(1)"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <span name="footer" class="dialog-footer">
        <el-button @click="cancelYCS">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog title="批量导入" v-model="addDialogVisible" width="400px">
      <el-upload
        ref="upload"
        v-loading="upload.isUploading"
        element-loading-text="正在上传模板 请稍候"
        :limit="1"
        action="#"
        :http-request="requestAddUpload"
        accept=".xlsx"
        :disabled="upload.isUploading"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip" style="color: red">
            提示：仅允许导入“xlsx”格式文件！
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="fetchFile(2)"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <span footer="footer" class="dialog-footer">
        <el-button @click="cancelPL">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import Pagination from '@/components/Pagination'

import {
  fetchCustomerList,
  fetchCustomerDetail,
  importCloudTax,
  importCustomerBranch
} from '@/api/customer/customer'
import CompanyItem from './modules/companyItem'
import { reactive, getCurrentInstance, toRefs } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter()
const { proxy } = getCurrentInstance()
const data = reactive({
  importDialogVisible: false,
  addDialogVisible: false,
  upload: {
    isUploading: false
  },
  content: '',
  loading: true,
  dropdown: '默认排序',
  total: 0,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    areaCode: '',
    keyword: '',
    orderByTime: '',
    orderByXj: '',
    parentId: ''
  },
  companyList: []
})
let {
  importDialogVisible,
  addDialogVisible,
  upload,
  content,
  loading,
  dropdown,
  total,
  queryParams,
  companyList
} = toRefs(data)

init()
async function init() {
  console.log(import.meta.env)
  content.value =
    route.currentRoute.value.query && route.currentRoute.value.query.keyword
      ? decodeURI(route.currentRoute.value.query.keyword)
      : ''
  if (route.currentRoute.value.query.flag == 'search') {
    // console.log(JSON.parse(localStorage.getItem('searchList')))
    let res = JSON.parse(localStorage.getItem('searchList'))
    companyList.value = res.rows.map(row => ({
      ...row,
      xj: parseInt(row.xj)
    }))
    loading.value = false
    total.value = res.total
  } else {
    await list()
  }
}
async function requestUpload(data) {
  upload.value.isUploading = true
  let formData = new FormData()
  formData.append('file', data.file)
  try {
    const res = await importCloudTax(formData)
    if (res.code === 200) {
      // console.log(res)
    } else {
      proxy.$modal.msgError(res.msg)
    }
    upload.value.isUploading = false
    importDialogVisible.value = false
    proxy.$refs.upload.clearFiles()
    await list()
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('上传文件服务异常 请重试')
    upload.value.isUploading = false
  }
}

function cancelYCS() {
  importDialogVisible.value = false
  proxy.$refs.upload.clearFiles()
}
async function requestAddUpload(data) {
  upload.value.isUploading = true
  let formData = new FormData()
  formData.append('file', data.file)
  try {
    const res = await importCustomerBranch(formData)
    if (res.code === 200) {
      // console.log(res)
    } else {
      proxy.$modal.msgError(res.msg)
    }
    upload.value.isUploading = false
    addDialogVisible.value = false
    proxy.$refs.upload.clearFiles()
    await list()
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('上传文件服务异常 请重试')
    upload.value.isUploading = false
  }
}

function cancelPL() {
  addDialogVisible.value = false
  proxy.$refs.upload.clearFiles()
}
/**
 * 分页刷新
 */
function pagination() {}

function toOrderManagement() {
  route.push({ path: '/xs/xzkh', query: { flag: 'addCustomers' } })
}
function to() {
  route.push({ path: '/xs/gjss', query: {} })
}

async function list() {
  try {
    loading.value = true
    queryParams.value.keyword = content
    const res = await fetchCustomerList(queryParams.value)
    // console.log(res);
    if (res.code === 200) {
      companyList.value = res.rows.map(row => ({
        ...row,
        xj: parseInt(row.xj)
      }))
      total.value = res.total
    } else {
      proxy.$modal.msgError('查询客户档案失败')
    }
    loading.value = false
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('接口异常')
    loading.value = false
  }
}

async function toSearch(param, value, name) {
  dropdown.value = name
  queryParams.value.areaCode = ''
  queryParams.value.orderByTime = ''
  queryParams.value.orderByXj = ''
  queryParams.value.parentId = ''
  if (param && value) {
    queryParams.value[param] = value
  }
  await list()
}

function toCustomerDetail(company) {
  route.push({
    path: '/xs/khdamx',
    query: { cusId: company.cusId }
  })
  // console.log(company)
  // const res = await fetchCustomerDetail(company.cusId)
  // console.log(res)
}
/** 下载模板操作 */
function fetchFile(index) {
  if (index == 1)
    window.location.href =
      'http://192.168.1.6:9000/erp/model/cloudtax/cloudtax.xlsx'
  else if (index == 2)
    window.location.href =
      'http://192.168.1.6:9000/erp/model/customer/customer.xlsx'
}
</script>

<style scoped lang="scss">
.page-wrapper {
  width: 100%;
  min-height: calc(100vh - 89px);
  height: calc(100vh - 89px);
  background-color: rgb(242, 242, 242);

  .page-header {
    box-shadow: 0 4px 12px rgb(40 120 255 / 11%), 0 3px 14px rgb(0 0 0 / 11%);

    .search {
      display: flex;
      padding: 15px 30px;
      background-color: white;

      .search-input {
        flex: 1;
        :deep .el-input__wrapper {
          padding: 0;
        }
        :deep .el-input .el-input__inner {
          height: 45px;
          border-radius: 8px;
          border: 2px solid #46a6ff;
          border-bottom-right-radius: 0;
          border-top-right-radius: 0;
          border-right: none;
          padding: 0 15px;
        }
      }

      .button-group {
        width: 300px;

        .search-text {
          margin-left: 20px;
        }

        .btn-search {
          width: 140px;
          border-radius: 6px;
          border-bottom-left-radius: 0;
          border-top-left-radius: 0;
          border-left: none !important;
          font-size: 16px;
          letter-spacing: 3px;
        }

        .btn-add {
          border-radius: 6px;
        }

        .button {
          height: 45px;
        }
      }
    }

    .tools {
      width: 100%;
      height: 50px;
      background-color: white;
      display: flex;
      padding-bottom: 10px;
      align-items: center;

      .count {
        display: inline-block;
        //line-height: 45px;
        padding-left: 30px;
        font-size: 14px;
      }

      .btn-group {
        margin-left: auto;
        margin-right: 30px;
        //display: inline-block;
        //margin-top: 6px;
        float: right;
      }
    }
  }
}

.footer {
  position: absolute;
  left: 0;
  bottom: 0;
  height: 55px;
  width: 100%;
  box-shadow: 0 4px 12px rgb(40 120 255 / 11%), 0 3px 14px rgb(0 0 0 / 11%);
  background-color: white;
}

.content {
  height: calc(100% - 100px);
  overflow-y: scroll;
  padding: 15px 30px;
}

.content .company-item:last-child {
  margin-bottom: 80px;
}

.pagination {
  margin-top: -0px;
  margin-right: 30px;
}
</style>
